package com.giggle.mybatis.Interceptor;

import com.giggle.common.snow.IdGenerater;
import com.giggle.mybatis.annotation.AutoGenegrateId;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.util.Properties;

/**
 * @author guozichen
 * @ClassName:
 * @Description: (雪花算法id生成器)
 * @date 2020/9/2 16:07
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class IdGeneraterInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        if (args.length == 2 && args[1] != null) {
            Object paramObject = args[1];
            Class<?> aClass = paramObject.getClass();
            AutoGenegrateId annotation = aClass.getAnnotation(AutoGenegrateId.class);
            if (annotation != null) {
                String name = annotation.name();
                Field declaredField = aClass.getDeclaredField(name);
                if (declaredField != null) {
                    declaredField.setAccessible(true);
                    declaredField.set(paramObject, IdGenerater.nextId());
                    args[1] = paramObject;
                } else {
                    throw new RuntimeException("注解[" + name + "] 的域在实体类中不存在");
                }
            }
        }
        Object proceed = invocation.proceed();
        return proceed;

    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
